package avicit.ma.ma.na.demomain.service;

import avicit.ma.ma.na.demomain.dao.DemoMainDAO;
import avicit.ma.ma.na.demomain.dto.DemoMainDTO;
import avicit.ma.ma.na.demomain.dto.DemoMainImportDTO;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.*;
import avicit.platform6.core.common.baseservice.BaseService;
import avicit.platform6.core.excel.ExcelUtil;
import avicit.platform6.core.excel.Map2Bo;
import avicit.platform6.core.excel.imp.entity.ExcelImportResult;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryReqBean;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * demoMainService类
 *
 * @author admin
 * @version V1.0.0
 * @date 2024-11-18 14:17:22
 * @since V1.0.0
 */
@Service
public class DemoMainService extends BaseService<DemoMainDAO, DemoMainDTO> {

  private static final Logger logger = LoggerFactory.getLogger(DemoMainService.class);

  @Autowired
  private DemoMainDAO demoMainDAO;

  @Autowired
  private ConvertColumnClient convertColumnClient;

  /**
   * 按条件分页查询
   * @param queryReqBean 查询条件
   * @return QueryRespBean<DemoMainDTO>
   */
  @Transactional(readOnly = true)
  public QueryRespBean<DemoMainDTO> findListByPage(QueryReqBean<DemoMainDTO> queryReqBean) {
    QueryRespBean<DemoMainDTO> queryRespBean = new QueryRespBean<>();
    List<DemoMainDTO> result = super.findByPage(queryReqBean);
    this.valueConvert(result);
    queryRespBean.setResultByList(result);
    return queryRespBean;
  }

  /**
   * 按条件查询
   *
   * @param queryReqBean 查询条件
   * @return List<DemoMainDTO>
   */
  @Transactional(readOnly = true)
  public List<DemoMainDTO> findList(QueryReqBean<DemoMainDTO> queryReqBean) {
    DemoMainDTO searchParams = super.getQueryEntity(queryReqBean);
    List<DemoMainDTO> result = super.findList(searchParams);
    this.valueConvert(result);
    return result;
  }

  /**
   * 通过主键查询单条记录
   *
   * @param id 主键id
   * @return DemoMainDTO
   */
  @Transactional(readOnly = true)
  @Override
  public DemoMainDTO get(String id) {
    DemoMainDTO result = super.get(id);
    //记录日志
    this.valueConvert(Arrays.asList(result));
    return result;
  }

  /**
   * 新增对象
   *
   * @param entity 保存对象
   * @return String
   */
  @Transactional
  @Override
  public String insert(DemoMainDTO entity) {
    entity.setId(ComUtil.getId());
    return super.insert(entity);
  }

  /**
   * 批量新增对象
   *
   * @param dtoList 保存对象集合
   * @return int
   */
  @Transactional
  @Override
  public int insertBatch(List<DemoMainDTO> dtoList) {
    return super.insertBatch(dtoList);
  }

  /**
   * 修改对象全部字段
   *
   * @param entity 修改对象
   * @return int
   */
  @Transactional
  @Override
  public int updateAll(DemoMainDTO entity) {
    if (entity == null) {
      throw new BusinessException("修改对象不能为空！");
    }
    if (StringUtils.isEmpty(entity.getId())) {
      throw new BusinessException("修改对象的id不能为空！");
    }
    return super.updateAll(entity);
  }

  /**
   * 修改对象部分字段
   *
   * @param entity 修改对象
   * @return int
   */
  @Transactional
  @Override
  public int updateSensitive(DemoMainDTO entity) {
    if (entity == null) {
      throw new BusinessException("修改对象不能为空！");
    }
    if (StringUtils.isEmpty(entity.getId())) {
      throw new BusinessException("修改对象的id不能为空！");
    }
    return super.updateSensitive(entity);
  }

  /**
   * 批量更新对象
   *
   * @param dtoList 修改对象集合
   * @return int
   */
  @Transactional
  @Override
  public int updateBatch(List<DemoMainDTO> dtoList) {
    return super.updateBatch(dtoList);
  }

  /**
   * 按主键单条删除
   *
   * @param id 主键id
   * @return int
   */
  @Transactional
  @Override
  public int delete(String id) {
    int count = super.delete(id);
    return count;
  }

  /**
   * 批量删除数据
   *
   * @param ids id的数组
   * @return int
   */
  @Transactional
  @Override
  public int deleteByIds(String[] ids) {
    int count = super.deleteByIds(ids);
    return count;
  }

  /**
   * 日志专用，内部方法，不再记录日志
   *
   * @param id 主键id
   * @return DemoMainDTO
   */
  private DemoMainDTO findById(String id) {
    return super.get(id);
  }

  /**
   * 批量导入
   * @return
   */
  @Transactional
  public ExcelImportResult importData(List<Map<String, String>> dataList, String formData) {
    List<DemoMainDTO> succesResult = new ArrayList<DemoMainDTO>();
    List<DemoMainImportDTO> errorResult = new ArrayList<DemoMainImportDTO>();
    Map<String, Object> formDataMap = new HashMap<String, Object>();
    if (StringUtils.isNotEmpty(formData)) {
      formDataMap = JsonUtil.parseJSON2Map(formData);
    }
    if (!CollectionUtils.isEmpty(dataList)) {
      Map<String, Map<String, String>> convertResultData = this.assembleData(dataList);
      for (Map<String, String> data : dataList) {
        if (StringUtils.isEmpty(data.get("errorInfo"))) {
          //业务校验
          DemoMainDTO dto = new DemoMainDTO();
          Map2Bo.map2Pojo(data, dto);
          succesResult.add(dto);
        } else {
          DemoMainImportDTO dtoImp = new DemoMainImportDTO();
          Map2Bo.map2Pojo(data, dtoImp);
          errorResult.add(dtoImp);
        }
      }
      this.revValueConvert(succesResult, convertResultData);
      this.insertBatch(succesResult);
    }
    ExcelImportResult excelImport = ExcelUtil.createUploadHis(succesResult, errorResult, DemoMainImportDTO.class, formDataMap);
    SysLogUtil.log(new DemoMainDTO().getLogTitle(), new DemoMainDTO().getLogTitle() + "共导入" + excelImport.getTotalRecord() + "条,导入成功" + excelImport.getSuccessRecord() + "条,导入失败" + excelImport.getFailRecord() + "条。", PlatformConstant.OpType.fileImport, PlatformConstant.OpResult.success, ComUtil.getId(), "demo_main");
    return excelImport;
  }

  /**
   * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
   *
   * @param entities
   */
  private void valueConvert(List<DemoMainDTO> entities) {
    //循环组装请求数据
    Map<String, Set<String>> convertFormData = new HashMap<>();
    for (DemoMainDTO temp : entities) {
      BusinessUtil.createConvertSet(convertFormData, "PLATFORM_FILE_SECRET_LEVEL", temp.getSecretLevel());
    }
    if (convertFormData.size() > 0) {
      //获取请求结果
      Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
      //循环设置Alias或Name的值
      for (DemoMainDTO temp : entities) {
        temp.setSecretLevelName(BusinessUtil.convertFormat(convertResultData, "PLATFORM_FILE_SECRET_LEVEL", temp.getSecretLevel()));
      }
    }
  }

  /**
   * 通过平台API将字段名称转换为值，包括通用选择组件、通用代码
   * 基础数据中用户默认使用用户编号转换，部门、岗位、角色默认使用编码进行转换，群组使用名称进行转换
   *
   * @param entities
   * @param convertResultData
   */
  private void revValueConvert(List<DemoMainDTO> entities, Map<String, Map<String, String>> convertResultData) {
    //循环设置Alias或Name的值
    for (DemoMainDTO temp : entities) {
      temp.setSecretLevel(BusinessUtil.convertFormat(convertResultData, "PLATFORM_FILE_SECRET_LEVEL", temp.getSecretLevelName()));
    }
  }

  /**
   * 通过平台API将字段名称转换为值，包括通用选择组件、通用代码提前组装数据
   *
   * @param dataList
   */
  private Map<String, Map<String, String>> assembleData(List<Map<String, String>> dataList) {
    //循环组装请求数据
    Map<String, Set<String>> convertFormData = new HashMap<>();
    for (Map<String, String> data : dataList) {
      BusinessUtil.createConvertSet(convertFormData, "PLATFORM_FILE_SECRET_LEVEL", data.get("secretLevelName"));
    }
    return convertColumnClient.convertCodeToId(convertFormData);
  }
}
